package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-jwt/db"
	"go-jwt/jwtconfig"
)

func main() {

	engine := gin.Default()
	engine.POST("/login", Certification(), func(context *gin.Context) {
		user := context.PostForm("user")
		fmt.Println(jwtconfig.MakeUserToken(user))
		context.String(200, "welcome register")
	})
	engine.GET("/", JWTHandler(), func(context *gin.Context) {
		context.String(200, "Hello World")
	})

	engine.GET("/test1", JWTHandler(), func(context *gin.Context) {
		context.String(200, "welcome index !")
	})

	engine.GET("/test2", JWTHandler(), func(context *gin.Context) {
		context.String(200, "welcome test")
	})
	engine.Run("127.0.0.1:80")
}

//定义权限认证中间件

func Certification() gin.HandlerFunc {
	return func(context *gin.Context) {
		//fmt.Println(context.PostForm("username"))
		var user db.User
		db.ConnMysql().Where("user = ?", context.PostForm("username")).Find(&user)
		//fmt.Println("user----------", user)
		//判断用户是否存在
		if user.User == "" {
			context.String(500, "用户名不存在!")
			context.Abort()
			//判断用户密码
		} else if user.Password != context.PostForm("password") {
			context.String(500, "用户名或密码错误!")
			context.Abort()
		} else {
			//fmt.Println("password-----------", user.Password)
			context.Next()
		}

	}
}

//jwt拦截器

func JWTHandler() gin.HandlerFunc {
	return func(context *gin.Context) {

		//引入jwt实现登录后的会话记录,登录会话发生登录完成之后
		//header获取token
		token := context.Request.Header.Get("token")
		if token == "" {
			context.String(302, "请求未携带token无法访问!")
			context.Abort()
		}
		//解析token
		claims, err := jwtconfig.ParserUserToken(token)
		if claims == nil || err != nil {
			context.String(401, "未携带有效token或已过期")
			context.Abort()
		} else {
			//context.Set("user", claims.Username)
			context.Next()

		}
	}
}
